/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-25 16:49:15
 * @LastEditTime: 2022-10-31 13:55:41
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 用户模块中间件
 */
const crypto = require('crypto');
const { query } = require('../service/users.service');
const { PASS_ALGORITHM, PASS_SECRET } = require('../utils/constant');
const { userFormateError, userLoginError, userDoesNotExist, invalidPassword, userRegisterError, userAlreadyExited } = require('../utils/errType');

/**
 * @description: 登录表单校验
 * @param {*} type - 1 为注册
 * 
 */
const userValidatorMiddleware = (type = 0) => (ctx, next) => {
  const { pass, phone, name } = ctx.request.body;
  const nameFlag = !type || name;//当为注册的时候需要校验用户名
  if (!phone || !pass || !nameFlag) return ctx.fail(userFormateError);
  return next();
}



/**
 * @description: 密码加密中间件
 */
const cryptoPasswordMiddleware = (ctx, next) => {
  try {
    const { pass } = ctx.request.body;
    ctx.request.body.cryptoPassword = crypto.createHmac(PASS_ALGORITHM, PASS_SECRET).update(pass).digest('hex')
    return next();
  } catch (err) {
    ctx.fail("密码错误！")
  }
}

/**
 * @description: 登录用户信息校验
 */
const verifyLoginMiddleware = async (ctx, next) => {
  try {
    const { phone, cryptoPassword: pass } = ctx.request.body;
    // const whereSql = "where id = ?";
    // let [user] = await queryUser(id, whereSql);
    let [user] = await query({ phone });
    if (!user) return ctx.fail(userDoesNotExist);
    if (pass != user.pass) return ctx.fail(invalidPassword);
    delete user.pass;
    ctx.state.userInfo = user;
    return next();
  } catch (err) {
    ctx.fail(userLoginError);
  }
}

const verifyRegisterMiddleware = async (ctx, next) => {
  try {
    const { phone } = ctx.request.body;
    let res = await query({ phone });
    if (res.length) return ctx.fail(userAlreadyExited);
    return next();
  } catch (err) {
    ctx.fail(userRegisterError);
  }
}

module.exports = {
  userValidatorMiddleware,
  cryptoPasswordMiddleware,
  verifyLoginMiddleware,
  verifyRegisterMiddleware
}
